import os
import win32com.client as win32
import pythoncom
from concurrent.futures import ThreadPoolExecutor, as_completed

# 将doc转换为docx
def convert_doc_to_docx(doc_file_path):
    try:
        # 初始化COM库
        pythoncom.CoInitialize()

        # 获取文件名和路径
        docx_file_path = doc_file_path.rsplit('.', 1)[0] + '.docx'

        # 使用win32com.client进行转换
        word = win32.gencache.EnsureDispatch('Word.Application')
        doc = word.Documents.Open(doc_file_path)
        doc.SaveAs(docx_file_path, FileFormat=16)  # 16表示docx格式
        doc.Close()
        word.Quit()

        # 删除原始doc文件
        os.remove(doc_file_path)

        return f"转换成功: {doc_file_path}"
    except Exception as e:
        return f"转换失败: {doc_file_path}, 错误信息: {str(e)}"
    finally:
        # 反初始化COM库
        pythoncom.CoUninitialize()

def batch_convert_docs_to_docx(directory, max_workers=5):
    # 获取目录下所有doc文件
    doc_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.doc')]

    if not doc_files:
        print("没有找到任何.doc文件")
        return

    # 使用多线程进行转换
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_file = {executor.submit(convert_doc_to_docx, file_path): file_path for file_path in doc_files}
        for future in as_completed(future_to_file):
            file_path = future_to_file[future]
            result = future.result()
            print(result)

if __name__ == "__main__":
    # 指定文件目录
    directory = r'F:\apk20250806\report'
    batch_convert_docs_to_docx(directory)
